/**
 * @Author: easten
 * @Created: 2024-07-21 00:52:45
 * @Description: 设施管理页面
 *
 */
import { ApiFacility } from "_common/api/iot/ApiFacility";
import { ApiStation } from "_common/api/iot/ApiStation";
import { PageParams, TreeDataModel } from "_common/DataType";
import { IotFacility } from "_common/entity";
import { AxiosInstance } from "axios";
import classNames from "classnames";
import TableTitle from "components/common/TableTitle";
import React, { useState, useEffect, useMemo } from "react";
import {
  Button,
  MessagePlugin,
  Popconfirm,
  Space,
  Table,
  Tag,
  Tree,
} from "tdesign-react";
import Styles from "./index.module.less";
import { FolderIcon, RefreshIcon } from "tdesign-icons-react";
import FacilityDrawer from "./FacilityDrawer";
import FacilityDesigner from "./FacilityDesigner";
export type IotFacilityCompProps = {
  axios: AxiosInstance;
  className?: string;
};
const IotFacilityComp: React.FC<IotFacilityCompProps> = (
  props: IotFacilityCompProps
) => {
  const { axios, className } = props;
  const [pageState, setPageState] = useState<PageParams>({
    pageNum: 1,
    pageSize: 10,
    total: 0,
  });
  const [selectedRowKeys, setSelectedRowKeys] = useState<(string | number)[]>([
    1, 2,
  ]);
  const [visible, setVisible] = useState(false);
  const [edit, setEdit] = useState(false);
  const [loading] = useState<boolean>(false);
  const [designerOpen, setDesignerOpen] = useState<boolean>(false);
  const [workshopList, setWorkshopList] = useState<IotFacility[]>([]);
  const [gatewayTree, setStationTree] = useState<TreeDataModel[]>([]);
  const [selectedStation, setSelectedStation] = useState<
    TreeDataModel | undefined
  >();
  const [selectedRow, setSelectedRow] = useState<IotFacility>();

  const apiFacility = new ApiFacility(axios);
  const apiStation = new ApiStation(axios);

  useEffect(() => {
    getStationList();
    return () => {};
  }, []);

  // 获取站点
  const getStationList = async () => {
    const response = await apiStation.getList();
    if (response && response.code == 200 && response.data) {
      setStationTree(
        response.data?.map((item) => {
          return {
            label: item.name!,
            value: item.id!,
          };
        })
      );
    }
  };

  function onSelectChange(value: (string | number)[]) {
    setSelectedRowKeys(value);
  }

  // 查询
  const getWorkshopList = async () => {
    const response = await apiFacility.getPage({
      ...pageState,
      id: selectedStation?.value,
    });
    if (response && response.code == 200 && response.data) {
      setWorkshopList(response.data.list);
      setPageState({
        ...pageState,
        total: response.data.total,
      });
    } else {
      setWorkshopList([]);
    }
  };

  useEffect(() => {
    getWorkshopList();
  }, [selectedStation]);

  useEffect(() => {
    getWorkshopList();
  }, [pageState.pageNum, pageState.pageSize]);

  const renderLabel = (node: any) => (
    <Tag
      theme="warning"
      variant="outline"
      icon={<FolderIcon color="#EF9735" />}
      size="small"
    >
      站点：{node.data.label}
    </Tag>
  );

  // 删除用户
  const deleteWorkshop = async (id: number) => {
    const response = await apiFacility.delete(id);
    if (response && response.code == 200 && response.data) {
      MessagePlugin.success("删除成功");
      getWorkshopList();
    }
  };

  const treeNode = useMemo(() => {
    return (
      <Tree
        data={gatewayTree}
        activable
        hover
        transition
        label={renderLabel}
        className="ml-0"
        onActive={(e, c) => {
          if (e.length == 0) {
            setSelectedStation(undefined);
          } else {
            setSelectedStation(c.node as any);
          }
        }}
      />
    );
  }, [gatewayTree, selectedStation]);

  return (
    <div className={classNames(className, "flex", "flex-row")}>
      <div className={classNames(Styles.stationTree)}>
        <TableTitle text="站点信息" />
        <div className="pt-4 pr-5 pl-0">
          {/* <Input suffixIcon={<SearchIcon />} placeholder='请输入关键词' /> */}
          {treeNode}
        </div>
      </div>
      <div className={classNames(Styles.WorkshopTable, "pl-5")}>
        <div className="flex flex-row justify-between mb-4">
          <TableTitle text="设施列表" />
          <Space>
            <Button
              onClick={() => {
                if (selectedStation == null) {
                  MessagePlugin.error("请选择站点");
                  return;
                }
                setVisible(true);
                setEdit(false);
              }}
            >
              新增设施
            </Button>
            <Button
              icon={<RefreshIcon />}
              variant="outline"
              onClick={() => {
                getWorkshopList();
              }}
            ></Button>
          </Space>
        </div>

        <Table
          bordered
          columns={[
            {
              align: "left",
              width: 80,
              ellipsis: true,
              colKey: "index",
              title: "序号",
              cell: ({ rowIndex }) => {
                let _index =
                  (pageState.pageNum - 1) * pageState.pageSize + rowIndex + 1;
                return <span>{_index}</span>;
              },
            },
            {
              align: "left",
              ellipsis: true,
              colKey: "name",
              title: "设施名称",
            },
            {
              align: "left",
              ellipsis: true,
              colKey: "code",
              title: "设施编号",
            },
            /* {
              align: "center",
              ellipsis: true,
              colKey: "dicType",
              title: "设施类型",
              cell({ row }) {
                return (
                  <Tag theme="success" variant="outline">
                    {row?.dicTypeInfo?.dictLabel}
                  </Tag>
                );
              },
            }, */
            {
              align: "left",
              ellipsis: true,
              colKey: "desc",
              title: "设施描述",
            },
            {
              align: "center",
              fixed: "right",
              width: 220,
              colKey: "op",
              title: "操作",
              cell({ row }) {
                return (
                  <>
                    <Button
                      theme="success"
                      variant="text"
                      size="small"
                      onClick={() => {
                        setDesignerOpen(true);
                        setSelectedRow(row);
                      }}
                    >
                      场景设计
                    </Button>
                    <Button
                      theme="success"
                      variant="text"
                      size="small"
                      onClick={() => {
                        setVisible(true);
                        setEdit(true);
                        setSelectedRow(row);
                      }}
                    >
                      编辑
                    </Button>
                    <Popconfirm
                      content="确认删除吗"
                      destroyOnClose
                      placement="top"
                      showArrow
                      theme="default"
                      onConfirm={() => deleteWorkshop(row.id)}
                    >
                      <Button theme="primary" variant="text" size="small">
                        删除
                      </Button>
                    </Popconfirm>
                  </>
                );
              },
            },
          ]}
          loading={loading}
          data={workshopList}
          rowKey="index"
          selectedRowKeys={selectedRowKeys}
          verticalAlign="middle"
          hover
          onSelectChange={onSelectChange}
          pagination={{
            pageSize: pageState.pageSize,
            total: pageState.total,
            current: pageState.pageNum,
            showJumper: true,
            onCurrentChange(current) {
              setPageState({
                ...pageState,
                pageNum: current,
              });
            },
            onPageSizeChange(size) {
              setPageState({
                ...pageState,
                pageSize: size,
              });
            },
          }}
        />
      </div>

      <FacilityDrawer
        onSuccess={() => {
          setVisible(false);
          getWorkshopList();
        }}
        open={visible}
        edit={edit}
        axios={axios}
        station={selectedStation}
        value={selectedRow}
      />
      <FacilityDesigner
        onSuccess={() => {
          setDesignerOpen(false);
        }}
        open={designerOpen}
        edit={edit}
        axios={axios}
        facility={selectedRow}
      />
    </div>
  );
};
export default IotFacilityComp;
